﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Library;
using System.IO;
using System.Collections;
using System.Data.SqlClient;
using System.Threading;
namespace QuanLyThi
{
    public partial class FrmNganHangCauHoi : Form
    {
        public static string mConnect = FrmMain.mConnect;
        private string msql = "";
        public DGC_Library mLibrary = new DGC_Library(mConnect);


        public FrmNganHangCauHoi()
        {
            InitializeComponent();
          
            LoadMon();
            txtsocau_TextChanged(null, null);
        }
        private void LoadMon()
        {
            msql = "Select b.MS_Mondaotao,b.Mondaotao" +
                   " from  tb_masodethi a inner join tb_mondaotao b" +
                   " on a.MS_Mondaotao=b.MS_Mondaotao";
            DataTable dt = mLibrary.GetDataTable(msql, "a");
            cmon.DataSource = dt;
            cmon.DisplayMember = "Mondaotao";
            cmon.ValueMember = "MS_Mondaotao";
        }
       

        private void LoadNoidung(RichTextBox rt, byte[] noidung)
        {
            Stream theFile = new MemoryStream(noidung);
            rt.LoadFile(theFile, RichTextBoxStreamType.RichText);
        }

        private void cmon_SelectionChangeCommitted(object sender, EventArgs e)
        {
            try
            {
                //Load Chu de
                msql = "Select a.MS_chudeCT, a.ChudeCT" +
                      "  from  tb_LoaichudeCT a inner join tb_Loaichude b" +
                      "  on a.MS_Loaichude=b.MS_Loaichude inner join tb_Cauhinh_chude c" +
                      "  on b.ms_Loaichude=c.ms_loaichude" +
                      "   where c.ms_mondaotao=" + cmon.SelectedValue.ToString() +
                      "  Order by a.ChudeCT";
                DataTable dt = mLibrary.GetDataTable(msql, "a");
                cchude.DataSource = dt;
                cchude.DisplayMember = "ChudeCT";
                cchude.ValueMember = "MS_chudeCT";

                //Load do kho
                msql = "Select a.MS_CapdoCT, a.tenmucdo +' - '+ convert(char(2),diem)+N' điểm' as" +
                       " Tenmucdo from  tb_CapdokhoCT a inner join tb_Capdokho b" +
                       " on a.MS_Capdo=b.MS_Capdo inner join tb_Cauhinhcapdo c" +
                       " on b.ms_Capdo=c.ms_capdo" +
                       " where c.ms_mondaotao=" + cmon.SelectedValue.ToString() +
                       " Order by a.Tenmucdo";
                DataTable dt1 = mLibrary.GetDataTable(msql, "a");
                cdokho.DataSource = dt1;
                cdokho.DisplayMember = "tenmucdo";
                cdokho.ValueMember = "MS_capdoCT";

                //Load cau hoi
                msql = "Select IDCauHoiCha,(case CauHoiCha when 0 then N'Câu số  '+ cast(cauhoi as nvarchar) else N'Câu số  '+ cast(cauhoi as nvarchar)+N' (Câu hỏi chính '+cast(IDCauHoiCha as nvarchar)+')' end) as fullname, cauhoi " +

                       " from tb_Nganhangdethi" +
                       " where CauhoiID=0 and " +
                       " MS_Mondaotao=" + cmon.SelectedValue.ToString() +
                       " order by cauhoi";
                DataTable dt2 = mLibrary.GetDataTable(msql, "a");
                list.AutoGenerateColumns = false;
                list.DataSource = dt2;

                //panel4.Controls.Clear();               
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void list_SelectionChanged(object sender, EventArgs e)
        {
            try
            {
                msql = "Select * from  tb_Nganhangdethi Where Ms_Mondaotao=" + cmon.SelectedValue.ToString() + " and cauhoi=" + list.CurrentRow.Cells["cauhoi"].Value.ToString() + " order by CauhoiID";
                DataTable dt = mLibrary.GetDataTable(msql, "a");
                if (dt.Rows.Count > 0)
                {
                    if (bool.Parse(dt.Rows[0]["CauHoiCha"].ToString()))
                        butXemCauHoiChinh.Visible = true;
                    else
                        butXemCauHoiChinh.Visible = false;
                    LoadNoidung(noidung, (byte[])dt.Rows[0]["noidung"]);
                    LoadCauHoiChon();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }
        private void LoadCauHoiChon()
        {
            try
            {
                msql = "Select * from  tb_Nganhangdethi Where Ms_Mondaotao=" + cmon.SelectedValue.ToString() + " and cauhoi=" + list.CurrentRow.Cells["cauhoi"].Value.ToString() + " order by CauhoiID";
                DataTable dt = mLibrary.GetDataTable(msql, "a");
                //noi dung               
                panel4.Controls.Clear();               

                for (int i = 1; i < dt.Rows.Count; i++)
                {
                    int hh = 45 * i;
                    RichTextBox ctrDapan = new RichTextBox();
                    panel4.Controls.Add(ctrDapan);
                    ctrDapan.Location = new System.Drawing.Point(26,-48+ hh);
                    ctrDapan.Name = "txtNoidung" + i;
                   
                    ctrDapan.Size = new System.Drawing.Size(794, 41);
                    ctrDapan.TabIndex = 0;                  
                    LoadNoidung(ctrDapan, (byte[])dt.Rows[i]["noidung"]);

                    //check
                    string dapan = dt.Rows[i]["ttdapan"].ToString();
                  
                    if (dt.Rows[0]["ttcauhoi"].ToString() == "0")//1 dap an
                    {
                        RadioButton DARadio = new RadioButton();
                        panel4.Controls.Add(DARadio);
                        DARadio.AutoSize = true;
                        DARadio.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                        DARadio.ForeColor = System.Drawing.Color.Red;
                        DARadio.Location = new System.Drawing.Point(3, -40 + hh);
                        DARadio.Name = "DARadio" + i;
                        DARadio.Size = new System.Drawing.Size(43, 19);
                        DARadio.TabIndex = 2;
                        DARadio.TabStop = true;
                        DARadio.UseVisualStyleBackColor = true;
                        if (dapan == "True") DARadio.Checked = true;
                       
                    }
                    else//nhieu dap an
                    {
                        CheckBox DACheck = new CheckBox();
                        panel4.Controls.Add(DACheck);
                        DACheck.AutoSize = true;
                        DACheck.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                        DACheck.ForeColor = System.Drawing.Color.Red;
                        DACheck.Location = new System.Drawing.Point(3, -40 + hh);
                        DACheck.Name = "DACheck" + i;
                        DACheck.Size = new System.Drawing.Size(43, 19);
                        DACheck.TabIndex = 2;
                        DACheck.TabStop = true;
                        DACheck.UseVisualStyleBackColor = true;
                        if (dapan == "True") DACheck.Checked = true;
                        
                    }
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());
            }
        }

        private void butsua_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dialog = MessageBox.Show("Bạn có muốn sửa thông tin câu hỏi này không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialog == DialogResult.Yes)
                {
                   //Xoa cau hoi
                    msql = "Delete from tb_Nganhangdethi Where Ms_Mondaotao=" + cmon.SelectedValue.ToString() + " and cauhoi=" + list.CurrentRow.Cells["cauhoi"].Value.ToString();
                    mLibrary.RunProc(msql);
                    //Lưu cau hoi lai
                    UpdateDatabase(noidung, 0, 0, 0, 0, 0);
                    foreach (Control rt in panel4.Controls)
                    {
                        if (rt is RichTextBox)
                        {
                            RichTextBox Rich = (RichTextBox)rt;
                            int thutucontrol = int.Parse(Rich.Name.Substring(rt.Name.Length - 1, 1)); 
                            int dapan = 0;                            
                            int chude=0;
                            int capdo=0;
                            int batbuoc=0;
                            foreach (Control tim in panel4.Controls)
                            {
                                if (tim is RadioButton)
                                {                                   
                                    RadioButton radio=(RadioButton)tim;
                                    if (radio.Name == "DARadio" + thutucontrol)
                                    {
                                        if (radio.Checked) dapan = 1;
                                        UpdateDatabase(Rich,0, dapan, chude, capdo, batbuoc);
                                        break;
                                    }                                   
                                }
                                if (tim is CheckBox)
                                {
                                    CheckBox check = (CheckBox)tim;
                                    if (check.Name == "DACheck" + thutucontrol)
                                    {
                                        if (check.Checked) dapan = 1;
                                        UpdateDatabase(Rich,1, dapan, chude, capdo, batbuoc);
                                        break;
                                    }                                    
                                }
                            }                           
                        }
                    }  
                    MessageBox.Show("Sửa thông tin câu hỏi thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Sửa thông tin câu hỏi không thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        public static byte[] StrToByteArray(string str)
        {
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            return encoding.GetBytes(str);
        }
        private void UpdateDatabase(RichTextBox rt, int loai,int dapan, int chude, int capdo, int batbuoc)
        {
            string strQuery = "exec Luu_Nganhangcauhoi @Ms_mondaotao, " +
                              "@cauhoi, @TTcauhoi, " +
                              "@noidung, @TTdapan,@MS_chudeCT,@MS_capdoCT,@Isbatbuoc";
            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.Parameters.Add("@Ms_mondaotao", SqlDbType.Int).Value = cmon.SelectedValue.ToString();
            cmd.Parameters.Add("@cauhoi", SqlDbType.Int).Value = list.CurrentRow.Cells["cauhoi"].Value.ToString();
            cmd.Parameters.Add("@TTcauhoi", SqlDbType.Int).Value = loai;
            cmd.Parameters.Add("@noidung", SqlDbType.Image).Value = StrToByteArray(rt.Rtf);
            cmd.Parameters.Add("@TTdapan", SqlDbType.Int).Value = dapan;
            cmd.Parameters.Add("@MS_chudeCT", SqlDbType.Int).Value = chude;
            cmd.Parameters.Add("@MS_capdoCT", SqlDbType.Int).Value = capdo;
            cmd.Parameters.Add("@Isbatbuoc", SqlDbType.Int).Value = batbuoc;
            InsertUpdateData(cmd);
        }
        private void InsertDatabase(RichTextBox rt,int cauhoi, int loai, int dapan, int chude, int capdo, int batbuoc)
        {
            string strQuery = "exec Luu_Nganhangcauhoi @Ms_mondaotao, " +
                              "@cauhoi, @TTcauhoi, " +
                              "@noidung, @TTdapan,@MS_chudeCT,@MS_capdoCT,@Isbatbuoc";
            SqlCommand cmd = new SqlCommand(strQuery);
            cmd.Parameters.Add("@Ms_mondaotao", SqlDbType.Int).Value = cmon.SelectedValue.ToString();
            cmd.Parameters.Add("@cauhoi", SqlDbType.Int).Value = cauhoi;
            cmd.Parameters.Add("@TTcauhoi", SqlDbType.Int).Value = loai;
            cmd.Parameters.Add("@noidung", SqlDbType.Image).Value = StrToByteArray(rt.Rtf);
            cmd.Parameters.Add("@TTdapan", SqlDbType.Int).Value = dapan;
            cmd.Parameters.Add("@MS_chudeCT", SqlDbType.Int).Value = chude;
            cmd.Parameters.Add("@MS_capdoCT", SqlDbType.Int).Value = capdo;
            cmd.Parameters.Add("@Isbatbuoc", SqlDbType.Int).Value = batbuoc;
            InsertUpdateData(cmd);
        }
       
        private Boolean InsertUpdateData(SqlCommand cmd)
        {
            SqlConnection con = new SqlConnection(mConnect);
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
            finally
            {
                con.Close();
                con.Dispose();
            }
        }

        private void txtsocau_TextChanged(object sender, EventArgs e)
        {
            try
            {
                if (txtsocau.Text == "") txtsocau.Text = "1";
                noidung.Clear();  
                int socau = int.Parse(txtsocau.Text);
                if (check1da.Checked)
                {
                    CreatCauHoi1Da(socau);
                }
                if (checknhieuda.Checked)
                {
                    CreatCauHoinDa(socau);
                }
                
            }
            catch (Exception ex)
            {                
              MessageBox.Show(ex.ToString());
            }
        }
       
        private void CreatCauHoi1Da(int socau)
        {
            panel4.Controls.Clear();               
            for (int i = 1; i <= socau; i++)
            {
                int hh = 45 * i;
                RichTextBox ctrDapan = new RichTextBox();
                panel4.Controls.Add(ctrDapan);
                ctrDapan.Location = new System.Drawing.Point(26, -48 + hh);
                ctrDapan.Name = "txtNoidung" + i;

                ctrDapan.Size = new System.Drawing.Size(794, 41);
                ctrDapan.TabIndex = 0;
               
                RadioButton DARadio = new RadioButton();
                panel4.Controls.Add(DARadio);
                DARadio.AutoSize = true;
                DARadio.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                DARadio.ForeColor = System.Drawing.Color.Red;
                DARadio.Location = new System.Drawing.Point(3, -40 + hh);
                DARadio.Name = "DARadio" + i;
                DARadio.Size = new System.Drawing.Size(43, 19);
                DARadio.TabIndex = 2;
                DARadio.TabStop = true;
                DARadio.UseVisualStyleBackColor = true;
            }
        }
        private void CreatCauHoinDa(int socau)
        {
            panel4.Controls.Clear();
           
            for (int i = 1; i <= socau; i++)
            {
                int hh = 45 * i;
                RichTextBox ctrDapan = new RichTextBox();
                panel4.Controls.Add(ctrDapan);
                ctrDapan.Location = new System.Drawing.Point(26, -48 + hh);
                ctrDapan.Name = "txtNoidung" + i;

                ctrDapan.Size = new System.Drawing.Size(794, 41);
                ctrDapan.TabIndex = 0;

                CheckBox DACheck = new CheckBox();
                panel4.Controls.Add(DACheck);
                DACheck.AutoSize = true;
                DACheck.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                DACheck.ForeColor = System.Drawing.Color.Red;
                DACheck.Location = new System.Drawing.Point(3, -40 + hh);
                DACheck.Name = "DACheck" + i;
                DACheck.Size = new System.Drawing.Size(43, 19);
                DACheck.TabIndex = 2;
                DACheck.TabStop = true;
                DACheck.UseVisualStyleBackColor = true;
            }
        }

        private void check1da_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (check1da.Checked)
                {
                  
                    CreatCauHoi1Da(int.Parse(txtsocau.Text));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void checknhieuda_CheckedChanged(object sender, EventArgs e)
        {
            try
            {
                if (checknhieuda.Checked)
                {
                    
                    CreatCauHoinDa(int.Parse(txtsocau.Text));
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void butthem_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dialog = MessageBox.Show("Bạn có muốn thêm thông tin câu hỏi này không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialog == DialogResult.Yes)
                {                   
                    //Lưu cau hoi lai
                    int cau = mLibrary.Timso_int("Select max(cauhoi)+1 from  tb_Nganhangdethi Where Ms_Mondaotao="+cmon.SelectedValue.ToString());
                    int loai = 0; if (checknhieuda.Checked) loai = 1;
                    InsertDatabase(noidung,cau, loai, 0, 0, 0, 0);
                    foreach (Control rt in panel4.Controls)
                    {
                        if (rt is RichTextBox)
                         {
                            RichTextBox Rich = (RichTextBox)rt;
                            int thutucontrol = int.Parse(Rich.Name.Substring(rt.Name.Length - 1, 1));
                            int dapan = 0;
                            int chude = 0;
                            int capdo = 0;
                            int batbuoc = 0;
                            foreach (Control tim in panel4.Controls)
                            {
                                if (tim is RadioButton)
                                {
                                    RadioButton radio = (RadioButton)tim;
                                    if (radio.Name == "DARadio" + thutucontrol)
                                    {
                                        if (radio.Checked) dapan = 1;
                                        InsertDatabase(Rich,cau, 0, dapan, chude, capdo, batbuoc);
                                        break;
                                    }
                                }
                                if (tim is CheckBox)
                                {
                                    CheckBox check = (CheckBox)tim;
                                    if (check.Name == "DACheck" + thutucontrol)
                                    {
                                        if (check.Checked) dapan = 1;
                                        InsertDatabase(Rich,cau, 1, dapan, chude, capdo, batbuoc);
                                        break;
                                    }
                                }
                            }
                        }
                    }  
                    MessageBox.Show("Lưu thông tin câu hỏi thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    cmon_SelectionChangeCommitted(null, null);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Lưu thông tin câu hỏi không thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void butxoa_Click(object sender, EventArgs e)
        {
            try
            {
                DialogResult dialog = MessageBox.Show("Bạn có muốn xóa thông tin câu hỏi này không?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dialog == DialogResult.Yes)
                {
                    msql = "Delete from tb_Nganhangdethi Where Ms_Mondaotao="+cmon.SelectedValue.ToString()+" and cauhoi="+list.CurrentRow.Cells["cauhoi"].Value.ToString();
                    mLibrary.RunProc(msql);
                    MessageBox.Show("Xóa thông tin câu hỏi thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    cmon_SelectionChangeCommitted(null, null);
                }
            }
            catch (Exception)
            {
                MessageBox.Show("Xóa thông tin câu hỏi không thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

      
     
       
        private void CreatCauHoinhieuluachon(int socau)
        {
            panel4.Controls.Clear();
            for (int i = 1; i <= socau; i++)
            {
                int hh = 45 * i;
                RichTextBox ctrDapan = new RichTextBox();
                panel4.Controls.Add(ctrDapan);
                ctrDapan.Location = new System.Drawing.Point(26, -48 + hh);
                ctrDapan.Name = "txtNoidung" + i;

                ctrDapan.Size = new System.Drawing.Size(794, 41);
                ctrDapan.TabIndex = 0;

                RadioButton DARadio = new RadioButton();
                panel4.Controls.Add(DARadio);
                DARadio.AutoSize = true;
                DARadio.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
                DARadio.ForeColor = System.Drawing.Color.Red;
                DARadio.Location = new System.Drawing.Point(3, -40 + hh);
                DARadio.Name = "DARadio" + i;
                DARadio.Size = new System.Drawing.Size(43, 19);
                DARadio.TabIndex = 2;
                DARadio.TabStop = true;
                DARadio.UseVisualStyleBackColor = true;
            }
        }

     

       






















        //BO SUNG RICHTEXTBOX



        public enum StampActions
        {
            EditedBy = 1,
            DateTime = 2,
            Custom = 4
        }
        //Used for looping
        private RichTextBox rtbTemp = new RichTextBox();

        #region Selection Change event
        [Description("Occurs when the selection is changed"),
        Category("Behavior")]
        // Raised in tb1 SelectionChanged event so that user can do useful things
        public event System.EventHandler SelChanged;
        #endregion

        #region Stamp Event Stuff
        [Description("Occurs when the stamp button is clicked"),
         Category("Behavior")]
        public event System.EventHandler Stamp;

        /// <summary>
        /// OnStamp event
        /// </summary>
        protected virtual void OnStamp(EventArgs e)
        {

            RichTextBox rt = new RichTextBox();
            //Duyet cac control dang duoc FOCUS
            if (noidung.Focused) rt = noidung;

            foreach (Control mrt in panel4.Controls)
            {
                if (mrt is RichTextBox)
                {
                    RichTextBox Rich = (RichTextBox)mrt;
                    if (Rich.Focused) rt = Rich;
                }
            }








            if (Stamp != null)
                Stamp(this, e);

            switch (StampAction)
            {
                case StampActions.EditedBy:
                    {
                        StringBuilder stamp = new StringBuilder(""); //holds our stamp text
                        if (rt.Text.Length > 0) stamp.Append("\r\n\r\n"); //add two lines for space
                        stamp.Append("Edited by ");
                        //use the CurrentPrincipal name if one exsist else use windows logon username
                        if (Thread.CurrentPrincipal == null || Thread.CurrentPrincipal.Identity == null || Thread.CurrentPrincipal.Identity.Name.Length <= 0)
                            stamp.Append(Environment.UserName);
                        else
                            stamp.Append(Thread.CurrentPrincipal.Identity.Name);
                        stamp.Append(" on " + DateTime.Now.ToLongDateString() + "\r\n");

                        rt.SelectionLength = 0; //unselect everything basicly
                        rt.SelectionStart = rt.Text.Length; //start new selection at the end of the text
                        rt.SelectionColor = this.StampColor; //make the selection blue
                        rt.SelectionFont = new Font(rt.SelectionFont, FontStyle.Bold); //set the selection font and style
                        rt.AppendText(stamp.ToString()); //add the stamp to the richtextbox
                        rt.Focus(); //set focus back on the richtextbox
                    } break; //end edited by stamp
                case StampActions.DateTime:
                    {
                        StringBuilder stamp = new StringBuilder(""); //holds our stamp text
                        if (rt.Text.Length > 0) stamp.Append("\r\n\r\n"); //add two lines for space
                        stamp.Append(DateTime.Now.ToLongDateString() + "\r\n");
                        rt.SelectionLength = 0; //unselect everything basicly
                        rt.SelectionStart = rt.Text.Length; //start new selection at the end of the text
                        rt.SelectionColor = this.StampColor; //make the selection blue
                        rt.SelectionFont = new Font(rt.SelectionFont, FontStyle.Bold); //set the selection font and style
                        rt.AppendText(stamp.ToString()); //add the stamp to the richtextbox
                        rt.Focus(); //set focus back on the richtextbox
                    } break;
            } //end select
        }
        #endregion



        #region Update Toolbar
        /// <summary>
        ///     Update the toolbar button statuses
        /// </summary>
        public void UpdateToolbar()
        {
            RichTextBox rt = new RichTextBox();
            //Duyet cac control dang duoc FOCUS
            if (noidung.Focused) rt = noidung;

            foreach (Control mrt in panel4.Controls)
            {
                if (mrt is RichTextBox)
                {
                    RichTextBox Rich = (RichTextBox)mrt;
                    if (Rich.Focused) rt = Rich;
                }
            }








            // Get the font, fontsize and style to apply to the toolbar buttons
            Font fnt = GetFontDetails(rt);
            // Set font style buttons to the styles applying to the entire selection
            FontStyle style = fnt.Style;

            //Set all the style buttons using the gathered style
            tbbBold.Pushed = fnt.Bold; //bold button
            tbbItalic.Pushed = fnt.Italic; //italic button
            tbbUnderline.Pushed = fnt.Underline; //underline button
            tbbStrikeout.Pushed = fnt.Strikeout; //strikeout button
            tbbLeft.Pushed = (rt.SelectionAlignment == HorizontalAlignment.Left); //justify left
            tbbCenter.Pushed = (rt.SelectionAlignment == HorizontalAlignment.Center); //justify center
            tbbRight.Pushed = (rt.SelectionAlignment == HorizontalAlignment.Right); //justify right

            //Check the correct color
            foreach (MenuItem mi in cmColors.MenuItems)
                mi.Checked = (rt.SelectionColor == Color.FromName(mi.Text));

            //Check the correct font
            foreach (MenuItem mi in cmFonts.MenuItems)
                mi.Checked = (fnt.FontFamily.Name == mi.Text);

            //Check the correct font size
            foreach (MenuItem mi in cmFontSizes.MenuItems)
                mi.Checked = ((int)fnt.SizeInPoints == float.Parse(mi.Text));
        }
        #endregion

        #region Update Toolbar Seperators
        private void UpdateToolbarSeperators()
        {
            //Save & Open
            if (!tbbSave.Visible && !tbbOpen.Visible)
                tbbSeparator3.Visible = false;
            else
                tbbSeparator3.Visible = true;

            //Font & Font Size
            if (!tbbFont.Visible && !tbbFontSize.Visible && !tbbColor.Visible)
                tbbSeparator5.Visible = false;
            else
                tbbSeparator5.Visible = true;

            //Bold, Italic, Underline, & Strikeout
            if (!tbbBold.Visible && !tbbItalic.Visible && !tbbUnderline.Visible && !tbbStrikeout.Visible)
                tbbSeparator1.Visible = false;
            else
                tbbSeparator1.Visible = true;

            //Left, Center, & Right
            if (!tbbLeft.Visible && !tbbCenter.Visible && !tbbRight.Visible)
                tbbSeparator2.Visible = false;
            else
                tbbSeparator2.Visible = true;

            //Undo & Redo
            if (!tbbUndo.Visible && !tbbRedo.Visible)
                tbbSeparator4.Visible = false;
            else
                tbbSeparator4.Visible = true;
        }
        #endregion



        #region Color Click
        /// <summary>
        ///     Change the richtextbox color
        /// </summary>
        private void Color_Click(object sender, System.EventArgs e)
        {
            RichTextBox rt = new RichTextBox();
            //Duyet cac control dang duoc FOCUS
            if (noidung.Focused) rt = noidung;

            foreach (Control mrt in panel4.Controls)
            {
                if (mrt is RichTextBox)
                {
                    RichTextBox Rich = (RichTextBox)mrt;
                    if (Rich.Focused) rt = Rich;
                }
            }

            //set the richtextbox color based on the name of the menu item
            ChangeFontColor(Color.FromName(((MenuItem)sender).Text),rt);
        }
        #endregion

        #region Font Click
        /// <summary>
        ///     Change the richtextbox font
        /// </summary>
        private void Font_Click(object sender, System.EventArgs e)
        {
            // Set the font for the entire selection
            ChangeFont(((MenuItem)sender).Text);
            
        }

       
        #endregion

        #region Font Size Click
        /// <summary>
        ///     Change the richtextbox font size
        /// </summary>
        private void FontSize_Click(object sender, System.EventArgs e)
        {
            //set the richtextbox font size based on the name of the menu item
            ChangeFontSize(float.Parse(((MenuItem)sender).Text));
        }
        #endregion



        #region Public Properties
        /// <summary>
        ///     The toolbar that is contained with-in the RichTextBoxExtened control
        /// </summary>
        [Description("The internal toolbar control"),
        Category("Internal Controls"),
        DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        public ToolBar Toolbar
        {
            get { return tb1; }
        }

        ///// <summary>
        /////     The RichTextBox that is contained with-in the RichTextBoxExtened control
        ///// </summary>
        //[Description("The internal richtextbox control"),
        //Category("Internal Controls"),
        //DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        //public RichTextBox RichTextBox
        //{
        //    get { return rtb1; }
        //}

        /// <summary>
        ///     Show the save button or not
        /// </summary>
        [Description("Show the save button or not"),
        Category("Appearance")]
        public bool ShowSave
        {
            get { return tbbSave.Visible; }
            set { tbbSave.Visible = value; UpdateToolbarSeperators(); }
        }

        /// <summary>
        ///    Show the open button or not 
        /// </summary>
        [Description("Show the open button or not"),
        Category("Appearance")]
        public bool ShowOpen
        {
            get { return tbbOpen.Visible; }
            set { tbbOpen.Visible = value; UpdateToolbarSeperators(); }
        }

        /// <summary>
        ///     Show the stamp button or not
        /// </summary>
        [Description("Show the stamp button or not"),
         Category("Appearance")]
        public bool ShowStamp
        {
            get { return tbbStamp.Visible; }
            set { tbbStamp.Visible = value; }
        }

        /// <summary>
        ///     Show the color button or not
        /// </summary>
        [Description("Show the color button or not"),
        Category("Appearance")]
        public bool ShowColors
        {
            get { return tbbColor.Visible; }
            set { tbbColor.Visible = value; }
        }

        /// <summary>
        ///     Show the undo button or not
        /// </summary>
        [Description("Show the undo button or not"),
        Category("Appearance")]
        public bool ShowUndo
        {
            get { return tbbUndo.Visible; }
            set { tbbUndo.Visible = value; UpdateToolbarSeperators(); }
        }

        /// <summary>
        ///     Show the redo button or not
        /// </summary>
        [Description("Show the redo button or not"),
        Category("Appearance")]
        public bool ShowRedo
        {
            get { return tbbRedo.Visible; }
            set { tbbRedo.Visible = value; UpdateToolbarSeperators(); }
        }

        /// <summary>
        ///     Show the bold button or not
        /// </summary>
        [Description("Show the bold button or not"),
        Category("Appearance")]
        public bool ShowBold
        {
            get { return tbbBold.Visible; }
            set { tbbBold.Visible = value; UpdateToolbarSeperators(); }
        }

        /// <summary>
        ///     Show the italic button or not
        /// </summary>
        [Description("Show the italic button or not"),
        Category("Appearance")]
        public bool ShowItalic
        {
            get { return tbbItalic.Visible; }
            set { tbbItalic.Visible = value; UpdateToolbarSeperators(); }
        }

        /// <summary>
        ///     Show the underline button or not
        /// </summary>
        [Description("Show the underline button or not"),
        Category("Appearance")]
        public bool ShowUnderline
        {
            get { return tbbUnderline.Visible; }
            set { tbbUnderline.Visible = value; UpdateToolbarSeperators(); }
        }

        /// <summary>
        ///     Show the strikeout button or not
        /// </summary>
        [Description("Show the strikeout button or not"),
        Category("Appearance")]
        public bool ShowStrikeout
        {
            get { return tbbStrikeout.Visible; }
            set { tbbStrikeout.Visible = value; UpdateToolbarSeperators(); }
        }

        /// <summary>
        ///     Show the left justify button or not
        /// </summary>
        [Description("Show the left justify button or not"),
        Category("Appearance")]
        public bool ShowLeftJustify
        {
            get { return tbbLeft.Visible; }
            set { tbbLeft.Visible = value; UpdateToolbarSeperators(); }
        }

        /// <summary>
        ///     Show the right justify button or not
        /// </summary>
        [Description("Show the right justify button or not"),
        Category("Appearance")]
        public bool ShowRightJustify
        {
            get { return tbbRight.Visible; }
            set { tbbRight.Visible = value; UpdateToolbarSeperators(); }
        }

        /// <summary>
        ///     Show the center justify button or not
        /// </summary>
        [Description("Show the center justify button or not"),
        Category("Appearance")]
        public bool ShowCenterJustify
        {
            get { return tbbCenter.Visible; }
            set { tbbCenter.Visible = value; UpdateToolbarSeperators(); }
        }

        /// <summary>
        ///     Determines how the stamp button will respond
        /// </summary>
        StampActions m_StampAction = StampActions.EditedBy;
        [Description("Determines how the stamp button will respond"),
        Category("Behavior")]
        public StampActions StampAction
        {
            get { return m_StampAction; }
            set { m_StampAction = value; }
        }

        /// <summary>
        ///     Color of the stamp text
        /// </summary>
        Color m_StampColor = Color.Blue;

        [Description("Color of the stamp text"),
        Category("Appearance")]
        public Color StampColor
        {
            get { return m_StampColor; }
            set { m_StampColor = value; }
        }

        /// <summary>
        ///     Show the font button or not
        /// </summary>
        [Description("Show the font button or not"),
        Category("Appearance")]
        public bool ShowFont
        {
            get { return tbbFont.Visible; }
            set { tbbFont.Visible = value; }
        }

        /// <summary>
        ///     Show the font size button or not
        /// </summary>
        [Description("Show the font size button or not"),
        Category("Appearance")]
        public bool ShowFontSize
        {
            get { return tbbFontSize.Visible; }
            set { tbbFontSize.Visible = value; }
        }

        /// <summary>
        ///     Show the cut button or not
        /// </summary>
        [Description("Show the cut button or not"),
        Category("Appearance")]
        public bool ShowCut
        {
            get { return tbbCut.Visible; }
            set { tbbCut.Visible = value; }
        }

        /// <summary>
        ///     Show the copy button or not
        /// </summary>
        [Description("Show the copy button or not"),
        Category("Appearance")]
        public bool ShowCopy
        {
            get { return tbbCopy.Visible; }
            set { tbbCopy.Visible = value; }
        }

        /// <summary>
        ///     Show the paste button or not
        /// </summary>
        [Description("Show the paste button or not"),
        Category("Appearance")]
        public bool ShowPaste
        {
            get { return tbbPaste.Visible; }
            set { tbbPaste.Visible = value; }
        }

        ///// <summary>
        /////     Detect URLs with-in the richtextbox
        ///// </summary>
        //[Description("Detect URLs with-in the richtextbox"),
        //Category("Behavior")]
        //public bool DetectURLs
        //{
        //    get { return rtb1.DetectUrls; }
        //    set { rtb1.DetectUrls = value; }
        //}

        ///// <summary>
        ///// Determines if the TAB key moves to the next control or enters a TAB character in the richtextbox
        ///// </summary>
        //[Description("Determines if the TAB key moves to the next control or enters a TAB character in the richtextbox"),
        //Category("Behavior")]
        //public bool AcceptsTab
        //{           
        //    get { return rtb1.AcceptsTab; }
        //    set { rtb1.AcceptsTab = value; }
        //}

        ///// <summary>
        ///// Determines if auto word selection is enabled
        ///// </summary>
        //[Description("Determines if auto word selection is enabled"),
        //Category("Behavior")]
        //public bool AutoWordSelection
        //{
        //    get { return rtb1.AutoWordSelection; }
        //    set { rtb1.AutoWordSelection = value; }
        //}

        ///// <summary>
        ///// Determines if this control can be edited
        ///// </summary>
        //[Description("Determines if this control can be edited"),
        //Category("Behavior")]
        //public bool ReadOnly
        //{
        //    get { return rtb1.ReadOnly; }
        //    set
        //    {
        //        tb1.Visible = !value;
        //        rtb1.ReadOnly = value;
        //    }
        //}

        private bool _showToolBarText;

        /// <summary>
        /// Determines if the buttons on the toolbar will show there text or not
        /// </summary>
        [Description("Determines if the buttons on the toolbar will show there text or not"),
        Category("Behavior")]
        public bool ShowToolBarText
        {
            get { return _showToolBarText; }
            set
            {
                _showToolBarText = value;

                if (_showToolBarText)
                {
                    tbbSave.Text = "Save";
                    tbbOpen.Text = "Open";
                    tbbBold.Text = "Bold";
                    tbbFont.Text = "Font";
                    tbbFontSize.Text = "Font Size";
                    tbbColor.Text = "Font Color";
                    tbbItalic.Text = "Italic";
                    tbbStrikeout.Text = "Strikeout";
                    tbbUnderline.Text = "Underline";
                    tbbLeft.Text = "Left";
                    tbbCenter.Text = "Center";
                    tbbRight.Text = "Right";
                    tbbUndo.Text = "Undo";
                    tbbRedo.Text = "Redo";
                    tbbCut.Text = "Cut";
                    tbbCopy.Text = "Copy";
                    tbbPaste.Text = "Paste";
                    tbbStamp.Text = "Stamp";
                }
                else
                {
                    tbbSave.Text = "";
                    tbbOpen.Text = "";
                    tbbBold.Text = "";
                    tbbFont.Text = "";
                    tbbFontSize.Text = "";
                    tbbColor.Text = "";
                    tbbItalic.Text = "";
                    tbbStrikeout.Text = "";
                    tbbUnderline.Text = "";
                    tbbLeft.Text = "";
                    tbbCenter.Text = "";
                    tbbRight.Text = "";
                    tbbUndo.Text = "";
                    tbbRedo.Text = "";
                    tbbCut.Text = "";
                    tbbCopy.Text = "";
                    tbbPaste.Text = "";
                    tbbStamp.Text = "";
                }

                this.Invalidate();
                this.Update();
            }
        }

        #endregion

        #region Change font
        /// <summary>
        ///     Change the richtextbox font for the current selection
        /// </summary>
        public void ChangeFont(string fontFamily)
        {
            RichTextBox rt = new RichTextBox();
            //Duyet cac control dang duoc FOCUS
            if (noidung.Focused) rt = noidung;

            foreach (Control mrt in panel4.Controls)
            {
                if (mrt is RichTextBox)
                {
                    RichTextBox Rich = (RichTextBox)mrt;
                    if (Rich.Focused) rt = Rich;
                }
            }

            //This method should handle cases that occur when multiple fonts/styles are selected
            // Parameters:-
            // fontFamily - the font to be applied, eg "Courier New"

            // Reason: The reason this method and the others exist is because
            // setting these items via the selection font doen't work because
            // a null selection font is returned for a selection with more 
            // than one font!

            int rtb1start = rt.SelectionStart;
            int len = rt.SelectionLength;
            int rtbTempStart = 0;

            // If len <= 1 and there is a selection font, amend and return
            if (len <= 1 && rt.SelectionFont != null)
            {
                rt.SelectionFont =
                    new Font(fontFamily, rt.SelectionFont.Size, rt.SelectionFont.Style);
                return;
            }

            // Step through the selected text one char at a time
            rtbTemp.Rtf = rt.SelectedRtf;
            for (int i = 0; i < len; ++i)
            {
                rtbTemp.Select(rtbTempStart + i, 1);
                rtbTemp.SelectionFont = new Font(fontFamily, rtbTemp.SelectionFont.Size, rtbTemp.SelectionFont.Style);
            }

            // Replace & reselect
            rtbTemp.Select(rtbTempStart, len);
            rt.SelectedRtf = rtbTemp.SelectedRtf;
            rt.Select(rtb1start, len);
            return;
        }
        #endregion

        #region Change font style
        /// <summary>
        ///     Change the richtextbox style for the current selection
        /// </summary>
        public void ChangeFontStyle(FontStyle style, bool add, RichTextBox rtb1)
        {
            //This method should handle cases that occur when multiple fonts/styles are selected
            // Parameters:-
            //	style - eg FontStyle.Bold
            //	add - IF true then add else remove

            // throw error if style isn't: bold, italic, strikeout or underline
            if (style != FontStyle.Bold
                && style != FontStyle.Italic
                && style != FontStyle.Strikeout
                && style != FontStyle.Underline)
                throw new System.InvalidProgramException("Invalid style parameter to ChangeFontStyle");

            int rtb1start = rtb1.SelectionStart;
            int len = rtb1.SelectionLength;
            int rtbTempStart = 0;

            //if len <= 1 and there is a selection font then just handle and return
            if (len <= 1 && rtb1.SelectionFont != null)
            {
                //add or remove style 
                if (add)
                    rtb1.SelectionFont = new Font(rtb1.SelectionFont, rtb1.SelectionFont.Style | style);
                else
                    rtb1.SelectionFont = new Font(rtb1.SelectionFont, rtb1.SelectionFont.Style & ~style);

                return;
            }

            // Step through the selected text one char at a time	
            rtbTemp.Rtf = rtb1.SelectedRtf;
            for (int i = 0; i < len; ++i)
            {
                rtbTemp.Select(rtbTempStart + i, 1);

                //add or remove style 
                if (add)
                    rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont, rtbTemp.SelectionFont.Style | style);
                else
                    rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont, rtbTemp.SelectionFont.Style & ~style);
            }

            // Replace & reselect
            rtbTemp.Select(rtbTempStart, len);
            rtb1.SelectedRtf = rtbTemp.SelectedRtf;
            rtb1.Select(rtb1start, len);
            return;
        }
        #endregion

        #region Change font size
        /// <summary>
        ///     Change the richtextbox font size for the current selection
        /// </summary>
        public void ChangeFontSize(float fontSize)
        {
            RichTextBox rt = new RichTextBox();
            //Duyet cac control dang duoc FOCUS
            if (noidung.Focused) rt = noidung;

            foreach (Control mrt in panel4.Controls)
            {
                if (mrt is RichTextBox)
                {
                    RichTextBox Rich = (RichTextBox)mrt;
                    if (Rich.Focused) rt = Rich;
                }
            }


            //This method should handle cases that occur when multiple fonts/styles are selected
            // Parameters:-
            // fontSize - the fontsize to be applied, eg 33.5

            if (fontSize <= 0.0)
                throw new System.InvalidProgramException("Invalid font size parameter to ChangeFontSize");

            int rtb1start = rt.SelectionStart;
            int len = rt.SelectionLength;
            int rtbTempStart = 0;

            // If len <= 1 and there is a selection font, amend and return
            if (len <= 1 && rt.SelectionFont != null)
            {
                rt.SelectionFont =
                    new Font(rt.SelectionFont.FontFamily, fontSize, rt.SelectionFont.Style);
                return;
            }

            // Step through the selected text one char at a time
            rtbTemp.Rtf = rt.SelectedRtf;
            for (int i = 0; i < len; ++i)
            {
                rtbTemp.Select(rtbTempStart + i, 1);
                rtbTemp.SelectionFont = new Font(rtbTemp.SelectionFont.FontFamily, fontSize, rtbTemp.SelectionFont.Style);
            }

            // Replace & reselect
            rtbTemp.Select(rtbTempStart, len);
            rt.SelectedRtf = rtbTemp.SelectedRtf;
            rt.Select(rtb1start, len);
            return;
        }
        #endregion

        #region Change font color
        /// <summary>
        ///     Change the richtextbox font color for the current selection
        /// </summary>
        public void ChangeFontColor(Color newColor,RichTextBox rt)
        {



            //This method should handle cases that occur when multiple fonts/styles are selected
            // Parameters:-
            //	newColor - eg Color.Red

            int rtb1start = rt.SelectionStart;
            int len = rt.SelectionLength;
            int rtbTempStart = 0;

            //if len <= 1 and there is a selection font then just handle and return
            if (len <= 1 && rt.SelectionFont != null)
            {
                rt.SelectionColor = newColor;
                return;
            }

            // Step through the selected text one char at a time	
            rtbTemp.Rtf = rt.SelectedRtf;
            for (int i = 0; i < len; ++i)
            {
                rtbTemp.Select(rtbTempStart + i, 1);

                //change color
                rtbTemp.SelectionColor = newColor;
            }

            // Replace & reselect
            rtbTemp.Select(rtbTempStart, len);
            rt.SelectedRtf = rtbTemp.SelectedRtf;
            rt.Select(rtb1start, len);
            return;
        }
        #endregion

      
       
        public Font GetFontDetails(RichTextBox rt)
        {
            //This method should handle cases that occur when multiple fonts/styles are selected

            int rtb1start = rt.SelectionStart;
            int len = rt.SelectionLength;
            int rtbTempStart = 0;

            if (len <= 1)
            {
                // Return the selection or default font
                if (rt.SelectionFont != null)
                    return rt.SelectionFont;
                else
                    return rt.Font;
            }

            // Step through the selected text one char at a time	
            // after setting defaults from first char
            rtbTemp.Rtf = rt.SelectedRtf;

            //Turn everything on so we can turn it off one by one
            FontStyle replystyle =
                FontStyle.Bold | FontStyle.Italic | FontStyle.Strikeout | FontStyle.Underline;

            // Set reply font, size and style to that of first char in selection.
            rtbTemp.Select(rtbTempStart, 1);
            string replyfont = rtbTemp.SelectionFont.Name;
            float replyfontsize = rtbTemp.SelectionFont.Size;
            replystyle = replystyle & rtbTemp.SelectionFont.Style;

            // Search the rest of the selection
            for (int i = 1; i < len; ++i)
            {
                rtbTemp.Select(rtbTempStart + i, 1);

                // Check reply for different style
                replystyle = replystyle & rtbTemp.SelectionFont.Style;

                // Check font
                if (replyfont != rtbTemp.SelectionFont.FontFamily.Name)
                    replyfont = "";

                // Check font size
                if (replyfontsize != rtbTemp.SelectionFont.Size)
                    replyfontsize = (float)0.0;
            }

            // Now set font and size if more than one font or font size was selected
            if (replyfont == "")
                replyfont = rtbTemp.Font.FontFamily.Name;

            if (replyfontsize == 0.0)
                replyfontsize = rtbTemp.Font.Size;

            // generate reply font
            Font reply
                = new Font(replyfont, replyfontsize, replystyle);

            return reply;
        }
        
        #region Keyboard Handler
        private void noidung_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            RichTextBox rt = new RichTextBox();
            //Duyet cac control dang duoc FOCUS
            if (noidung.Focused) rt = noidung;

            foreach (Control mrt in panel4.Controls)
            {
                if (mrt is RichTextBox)
                {
                    RichTextBox Rich = (RichTextBox)mrt;
                    if (Rich.Focused) rt = Rich;
                }
            }




            if (e.Modifiers == Keys.Control)
            {
                ToolBarButton tbb = null;

                switch (e.KeyCode)
                {
                    case Keys.B:
                        tbb = this.tbbBold;
                        break;
                    case Keys.I:
                        tbb = this.tbbItalic;
                        break;
                    case Keys.S:
                        tbb = this.tbbStamp;
                        break;
                    case Keys.U:
                        tbb = this.tbbUnderline;
                        break;
                    case Keys.OemMinus:
                        tbb = this.tbbStrikeout;
                        break;
                }

                if (tbb != null)
                {
                    if (e.KeyCode != Keys.S) tbb.Pushed = !tbb.Pushed;
                    tb1_ButtonClick(null, new ToolBarButtonClickEventArgs(tbb));
                }
            }

            //Insert a tab if the tab key was pressed.
            /* NOTE: This was needed because in rtb1_KeyPress I tell the richtextbox not
             * to handle tab events.  I do that because CTRL+I inserts a tab for some
             * strange reason.  What was MicroSoft thinking?
             * Richard Parsons 02/08/2007
             */
            if (e.KeyCode == Keys.Tab)
                rt.SelectedText = "\t";

        }

        private void noidung_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if ((int)e.KeyChar == 9)
                e.Handled = true; // Stops Ctrl+I from inserting a tab (char HT) into the richtextbox
        }
       
        
        #endregion

       




        #region Link Clicked
        /// <summary>
        /// Starts the default browser if a link is clicked
        /// </summary>
        private void noidung_LinkClicked(object sender, System.Windows.Forms.LinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(e.LinkText);
        }
        #endregion


        /// <summary>
        ///		Change the toolbar buttons when new text is selected
        ///		and raise event SelChanged
        /// </summary>
        private void noidung_SelectionChanged(object sender, System.EventArgs e)
        {
            //Update the toolbar buttons
            UpdateToolbar();

            //Send the SelChangedEvent
            if (SelChanged != null)
                SelChanged(this, e);
        }
       
        /// <summary>
        ///     Handler for the toolbar button click event
        /// </summary>
        private void tb1_ButtonClick(object sender, System.Windows.Forms.ToolBarButtonClickEventArgs e)
        {
            RichTextBox rt = new RichTextBox();
            //Duyet cac control dang duoc FOCUS
            if (noidung.Focused) rt = noidung;
            
            foreach (Control mrt in panel4.Controls)
            {
                if (mrt is RichTextBox)
                {
                    RichTextBox Rich = (RichTextBox)mrt;
                    if (Rich.Focused) rt = Rich;                   
                }
            }






            // true if style to be added
            // false to remove style
            bool add = e.Button.Pushed;

            //Switch based on the tag of the button pressed
            switch (e.Button.Tag.ToString().ToLower())
            {
                case "font":
                    ChangeFont(tbbFont.Text);                 
                    break;
                case "font size":
                    ChangeFontSize(float.Parse(tbbFontSize.Text));            
                    break;
                    
                case "bold":
                    ChangeFontStyle(FontStyle.Bold, add, rt);
                    break;
                case "italic":
                    ChangeFontStyle(FontStyle.Italic, add, rt);
                    break;
                case "underline":
                    ChangeFontStyle(FontStyle.Underline, add, rt);
                    break;
                case "strikeout":
                    ChangeFontStyle(FontStyle.Strikeout, add, rt);
                    break;
                case "left":
                    //change horizontal alignment to left
                    rt.SelectionAlignment = HorizontalAlignment.Left;
                    tbbCenter.Pushed = false;
                    tbbRight.Pushed = false;
                    break;
                case "center":
                    //change horizontal alignment to center
                    tbbLeft.Pushed = false;
                    rt.SelectionAlignment = HorizontalAlignment.Center;
                    tbbRight.Pushed = false;
                    break;
                case "right":
                    //change horizontal alignment to right
                    tbbLeft.Pushed = false;
                    tbbCenter.Pushed = false;
                    rt.SelectionAlignment = HorizontalAlignment.Right;
                    break;
                case "edit stamp":
                    OnStamp(new EventArgs()); //send stamp event
                    break;
                case "color":
                    rt.SelectionColor = Color.Black;
                    break;
                case "undo":
                    rt.Undo();
                    break;
                case "redo":
                    rt.Redo();
                    break;
                case "open":
                    try
                    {
                        if (ofd1.ShowDialog() == DialogResult.OK && ofd1.FileName.Length > 0)
                            if (System.IO.Path.GetExtension(ofd1.FileName).ToLower().Equals(".rtf"))
                                rt.LoadFile(ofd1.FileName, RichTextBoxStreamType.RichText);
                            else
                                rt.LoadFile(ofd1.FileName, RichTextBoxStreamType.PlainText);
                    }
                    catch (ArgumentException ae)
                    {
                        if (ae.Message == "Invalid file format.")
                            MessageBox.Show("There was an error loading the file: " + ofd1.FileName);
                    }
                    break;
                case "save":
                    if (sfd1.ShowDialog() == DialogResult.OK && sfd1.FileName.Length > 0)
                        if (System.IO.Path.GetExtension(sfd1.FileName).ToLower().Equals(".rtf"))
                            rt.SaveFile(sfd1.FileName);
                        else
                            rt.SaveFile(sfd1.FileName, RichTextBoxStreamType.PlainText);
                    break;
                case "cut":
                    {
                        if (rt.SelectedText.Length <= 0) break;
                        rt.Cut();
                        break;
                    }
                case "copy":
                    {
                        if (rt.SelectedText.Length <= 0) break;
                        rt.Copy();
                        break;
                    }
                case "paste":
                    {
                        try
                        {
                            rt.Paste();
                        }
                        catch
                        {
                            MessageBox.Show("Paste Failed");
                        }
                        break;
                    }
                case "image":
                    {
                        OpenFileDialog _dialog = new OpenFileDialog();
                        _dialog.Filter = "All Image Files|*.bmp;*.ico;*.gif;*.jpeg;*.jpg;*.png;*.tif;*.tiff|" +
                                         "Windows Bitmap(*.bmp)|*.bmp|" +
                                         "Windows Icon(*.ico)|*.ico|" +
                                         "Graphics Interchange Format (*.gif)|(*.gif)|" +
                                         "JPEG File Interchange Format (*.jpg)|*.jpg;*.jpeg|" +
                                         "Portable Network Graphics (*.png)|*.png|" +
                                         "Tag Image File Format (*.tif)|*.tif;*.tiff";
                        if (DialogResult.OK == _dialog.ShowDialog(this))
                        {
                            try
                            {
                                //// If file is an icon
                                //if (_dialog.FileName.ToUpper().EndsWith(".ICO"))
                                //{
                                //    // Create a new icon, get it's handle, and create a bitmap from
                                //    // its handle
                                //    rtBox_Main.InsertImage(Bitmap.FromHicon((new Icon(_dialog.FileName)).Handle));
                                //}
                                //else
                                //{
                                //    // Create a bitmap from the filename
                                //    rtBox_Main.InsertImage(Image.FromFile(_dialog.FileName));
                                //}


                                Image img = Image.FromFile(_dialog.FileName);
                                IDataObject orgData = Clipboard.GetDataObject();
                                Clipboard.SetImage(img);
                                rt.Paste();
                            }
                            catch (Exception _e)
                            {
                                MessageBox.Show("The file could not be opened:\n\n" + _e.Message, "File Open Error");
                            }
                        }
                        break;
                    }

                case "word":
                    {
                        OpenFileDialog _dialog = new OpenFileDialog();
                        _dialog.Filter = "Word File|*.rtf";

                        if (DialogResult.OK == _dialog.ShowDialog(this))
                        {
                            try
                            {

                                rt.LoadFile(_dialog.FileName);
                            }
                            catch (Exception _e)
                            {
                                MessageBox.Show("The file could not be opened:\n\n" + _e.Message, "File Open Error");
                            }
                        }
                        break;
                    }
                case "math":
                    {

                        try
                        {

                            System.Diagnostics.Process Proc = new System.Diagnostics.Process();
                            Proc.StartInfo.FileName = Application.StartupPath + "\\MathType\\MathType.exe";
                            Proc.Start();
                        }
                        catch (Exception _e)
                        {
                            MessageBox.Show("Không thể thực thi:\n\n" + _e.Message, "Thông báo");
                        }

                        break;
                    }
            } //end select
        }

        //KHOI TAO SU KIEN
        void KhoiTaoSuKienChoRichTextbox(RichTextBox rt)
        {
           rt.SelectionChanged+=new EventHandler(rt_SelectionChanged);
           rt.KeyPress += new KeyPressEventHandler(rt_KeyPress);
           rt.KeyDown += new KeyEventHandler(rt_KeyDown);
           rt.LinkClicked += new LinkClickedEventHandler(rt_LinkClicked);
        }
        private void rt_LinkClicked(object sender, System.Windows.Forms.LinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(e.LinkText);
        }
        private void rt_SelectionChanged(object sender, System.EventArgs e)
        {
            //Update the toolbar buttons
            UpdateToolbar();

            //Send the SelChangedEvent
            if (SelChanged != null)
                SelChanged(this, e);
        }
        private void rt_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            RichTextBox rt = new RichTextBox();
            //Duyet cac control dang duoc FOCUS
            if (noidung.Focused) rt = noidung;

            foreach (Control mrt in panel4.Controls)
            {
                if (mrt is RichTextBox)
                {
                    RichTextBox Rich = (RichTextBox)mrt;
                    if (Rich.Focused) rt = Rich;
                }
            }




            if (e.Modifiers == Keys.Control)
            {
                ToolBarButton tbb = null;

                switch (e.KeyCode)
                {
                    case Keys.B:
                        tbb = this.tbbBold;
                        break;
                    case Keys.I:
                        tbb = this.tbbItalic;
                        break;
                    case Keys.S:
                        tbb = this.tbbStamp;
                        break;
                    case Keys.U:
                        tbb = this.tbbUnderline;
                        break;
                    case Keys.OemMinus:
                        tbb = this.tbbStrikeout;
                        break;
                }

                if (tbb != null)
                {
                    if (e.KeyCode != Keys.S) tbb.Pushed = !tbb.Pushed;
                    tb1_ButtonClick(null, new ToolBarButtonClickEventArgs(tbb));
                }
            }

            //Insert a tab if the tab key was pressed.
            /* NOTE: This was needed because in rtb1_KeyPress I tell the richtextbox not
             * to handle tab events.  I do that because CTRL+I inserts a tab for some
             * strange reason.  What was MicroSoft thinking?
             * Richard Parsons 02/08/2007
             */
            if (e.KeyCode == Keys.Tab)
                rt.SelectedText = "\t";

        }

        private void rt_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if ((int)e.KeyChar == 9)
                e.Handled = true; // Stops Ctrl+I from inserting a tab (char HT) into the richtextbox
        }

        private void butCauHoiDacBiet_Click(object sender, EventArgs e)
        {
            QuanLyThi.BienSoanDeThi.FrmCauHoiTongQuat frm = new QuanLyThi.BienSoanDeThi.FrmCauHoiTongQuat(cmon.SelectedValue.ToString());
            frm.ShowDialog();
        }

        private void cmFonts_Collapse(object sender, EventArgs e)
        {

        }

        private void cmFonts_Popup(object sender, EventArgs e)
        {
           

        }

        private void butXemCauHoiChinh_Click(object sender, EventArgs e)
        {
            try
            {
                int IDCauHoiCha = int.Parse(list.CurrentRow.Cells["cIDCauHoiCha"].Value.ToString());
                QuanLyThi.BienSoanDeThi.FrmCauHoiTongQuat frm = new QuanLyThi.BienSoanDeThi.FrmCauHoiTongQuat(cmon.SelectedValue.ToString(),true,IDCauHoiCha);
                frm.ShowDialog();
            }
            catch (Exception ex)
            {

                MessageBox.Show("Xem lại,có lỗi xãy ra", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
       







    }
}
